package com.str.config;

import com.str.utils.Retcode;
import com.str.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 拦截参数校验失败后的异常，统一结构返回
 * @author zhangWu
 * @date 2022/3/16 14:56
 */
@Slf4j
@RestControllerAdvice
public class ControllerAdvice {
    /**
     * 拦截表单参数校验
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({BindException.class})
    public ResponseVO bindException(BindException e){
        BindingResult bindingResult = e.getBindingResult();
        String msg = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
        log.error("表单参数校验异常：{}",msg);
        return new ResponseVO(Retcode.PARAM_ERROR.code(),String.format(Retcode.PARAM_ERROR.msg(),msg),null);
    }

    /**
     * 拦截json参数校验
     * @param e MethodArgumentNotValidException
     * @return 返回结果
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseVO bindException(MethodArgumentNotValidException e){
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        log.error("json参数校验异常：{}",message);
        return new ResponseVO(Retcode.PARAM_ERROR.code(),String.format(Retcode.PARAM_ERROR.msg(),message),null);
    }
    /**
     * 拦截未知的运行时异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RuntimeException.class)
    public Object notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return new ResponseVO(Retcode.SYSTEM_EXCEPTION.code(),String.format(e.getMessage()),null);
    }
}
